package com.wsc.wisdomchina.Tools;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;

import com.wsc.wisdomchina.BuildConfig;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.activitity.HomeActivity;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.javaBean.UpdateInfo;
import com.wsc.wisdomchina.view.iphoneDialogBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 
 * @Description 更新管理类
 * @author jaily.zhang
 * @date 2014-7-24 上午9:39:31
 * @version V1.3.1
 */
public class UpdateManager {
	private Context mContext;
	private Dialog noticeDialog;// 下载提示对话框
	private Boolean interceptFlag = false;// 标记用户是否在下载过程中取消下载
	private Thread downloadApkThread = null;// 下载线程
	private final int DOWNLOAD_OVER = 2;// 标记下载完成
	private String versionName;// 版本号
	private UpdateInfo updateInfo;// 版本信息类
	private ProgressDialog pd; // 进度条对话框
	private Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWNLOAD_OVER:
				// 安装程序
				installApk();
				break;

			}
		}
	};

	private File cacheDir;

	/**
	 * 
	 * Creates a new instance of UpdateManager. Description
	 * 
	 * @param context
	 */
	public UpdateManager(Context context, UpdateInfo updateInfo, String versionname) {
		// TODO Auto-generated constructor stub
		this.mContext = context;
		this.updateInfo = updateInfo;
		this.versionName = versionname;

		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
			cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), Constant.wsc_downLoadfile);
		else
			cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();

	}

	/**
	 * 
	 * @Description 检查是否有版本需要更新，具体比较版本xml
	 * @author jaily.zhang
	 */
	public void checkUpdate() {
		// 到服务器检查软件是否有版本
		// 如果有，则
		if (versionName.compareToIgnoreCase(updateInfo.getVersionCode()) < 0) {
			showNoticeDialog();
		}
	}

	/**
	 * 
	 * @Description 显示版本更新对话框
	 * @author jaily.zhang
	 */
	private void showNoticeDialog() {

		iphoneDialogBuilder idb = new iphoneDialogBuilder(mContext);
		idb.setTitle("版本更新");
		idb.setMessage(updateInfo.getContent());
		idb.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				downloadLatestVersionApk();
				Tools.setSharedPreferencesboolen(Constant.isUpdate, true,mContext);
			}
		});

/*		idb.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				Tools.setSharedPreferencesboolen(Constant.isUpdate, true,mContext);
			}
		});*/
        idb.create().setCancelable(false);
		idb.create().setCanceledOnTouchOutside(false);
		idb.show();

	}

	/**
	 * 
	 * @Description 下载最新的apk 文件
	 * @author jaily.zhang
	 */
	private void downloadLatestVersionApk() {

		pd = new ProgressDialog(mContext);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setTitle("更新");
		pd.setMessage("下载进度");
		pd.show();
		pd.setCanceledOnTouchOutside(false);
		downloadApkThread = new Thread(downloadApkRunnable);
		downloadApkThread.start();
	}

	/**
	 * apk 文件下载线程
	 */
	private Runnable downloadApkRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			URL url;
			try {
				url = new URL(updateInfo.getUrl());
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				conn.connect();

				int length = conn.getContentLength();

				int divdleng = 0;
				if (length < 1024) {
					divdleng = 1;
				}
				// 以K为单位
				else if (length >= 1024 && length < 1024 * 1024) {
					divdleng = 1024;
				}

				// 以M为单位
				else if (length >= 1024 * 1024 && length < 1024 * 1024 * 1024) {
					divdleng = 1024 * 1024;
				}
				// 以G为单位
				else {
					divdleng = 1024 * 1024 * 1024;
				}

				pd.setProgressNumberFormat("%1d kb/%2d kb");
				pd.setMax((int) Tools.div(length, 1024));
				InputStream is = conn.getInputStream();

				File apkFile = new File(cacheDir, "wscchina.apk");
				FileOutputStream out = new FileOutputStream(apkFile);
				int readnum = 0;
				byte[] buffer = new byte[1024];
				int total = 0;
				do {
					readnum = is.read(buffer);
					total += readnum;
					// 获取当前下载量
					pd.setProgress((int) Tools.div(total, 1024));
					if (readnum <= 0) {
						// 下载结束
						mhandler.sendEmptyMessage(DOWNLOAD_OVER);
						pd.dismiss();
						break;
					}
					out.write(buffer, 0, readnum);
				} while (!interceptFlag);

				is.close();
				out.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};

	/**
	 * 
	 * @Description 安装下载的apk文件
	 * @author jaily.zhang
	 */
	private void installApk() {
		File file = new File(cacheDir, "wscchina.apk");
		if (!file.exists()) {
			return;
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);

		//判断是否是AndroidN以及更高的版本
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Uri contentUri =FileProvider.getUriForFile(mContext, "com.wsc.wisdomchina.fileprovider", file);
			intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
		} else {
			intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		}
		Tools.setSharedPreferencesboolen(Constant.isFirstIn, true,mContext);
		mContext.startActivity(intent);
	}

	public void downloadSetting() {
		pd = new ProgressDialog(mContext);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setTitle("更新");
		pd.setMessage("下载进度");
		pd.show();
		pd.setCanceledOnTouchOutside(false);
		downloadApkThread = new Thread(downloadApkRunnable);
		downloadApkThread.start();
	}
}
